import os
import django
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "baoxian.settings")
django.setup()

from langchain.tools import tool
from insurance.models import InsuranceInfo, ClaimOrder

@tool
def alipay_transfer(id_number: str, claim_amount: str) -> str:
    """
    根据身份证号和理赔金额查找理赔订单，支付宝转账并更新订单状态。
    """
    print("\n[调试1] 当前匹配的待支付订单：")
    for order in ClaimOrder.objects.filter(status='待支付'):
        print(f"id: {order.id}, 保险人身份证: {order.insurance.id_number}, 理赔金额: '{order.claim_amount}', 状态: {order.status}")
    print(f"[调试1] 传入参数 id_number: '{id_number}', claim_amount: '{claim_amount}'\n")

    claim_order = ClaimOrder.objects.filter(
        insurance__id_number=id_number,
        claim_amount=str(claim_amount),
        status='待支付'
    ).first()

    if not claim_order:
        return "未找到符合条件的待转账理赔订单"

    # 商家账户写死
    merchant_account = "ouciqb3604@sandbox.com"
    user_account = claim_order.insurance.alipay_account
    amount = claim_order.claim_amount

    # ====== 支付宝转账集成开始 ======
    from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
    from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
    from alipay.aop.api.request.AlipayFundTransToaccountTransferRequest import AlipayFundTransToaccountTransferRequest
    import uuid
    from cryptography.hazmat.primitives import serialization

    # 配置参数（请替换为你的真实参数）
    client_config = AlipayClientConfig()
    # ====== 支付宝沙箱环境配置开始 ======
    # 沙箱网关地址
    client_config.server_url = "https://openapi.alipaydev.com/gateway.do"
    # 沙箱应用AppID（请在支付宝开放平台沙箱环境获取）
    client_config.app_id = "9021000150657773"
    # 沙箱应用私钥（PEM格式，带头尾，多行字符串）
#     client_config.app_private_key = """
# -----BEGIN PRIVATE KEY-----
# MIIEowIBAAKCAQEAiIEDd3c0DxRnTVLij6GqxjduirR9uvO5NdG4Qu8YIoIu8m4D7jWYo2rvZhMI/ZGNXriSfGR7ESVXhRAWmXTpMljP1yE9Ze9jg8RouLOUCcxm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Og6XY+MrKw0W1lP7OZViZVi1ljICyHyiiEnkECgYA3yTln1BYcb2IUEFm3OQLT0Zzlk9nwCWj56d8+BTwoXdHT5xVkD9ZMFKvj84qT6r33/yFDw7J/pS3q+cLKhUjBk7cY9BrRv7mDv8n0wx+lXGM4A94jXXYST/DVDVEGpYUvIDDm9hgXATf1rEeINVB6LSLF8poU71C1o4Vv/v8LRwKBgAO9Tl3K2SlGPa5TQoDoBfaMT7jJthQhVM9dtPo3SeHlv8/mXeKOHiQg72YEznK8pzDdKi5jv9EzrBh9ZOGXAGmys/u9bmTqNBsSZ+by6If39NavUoZpWIFpYSBzgAgzWN6h4Coqcu0bsoZRcOl12s977jtvCAe/6dXqUK5RXTfi
# -----END PRIVATE KEY-----
# """
    with open("D:\model\P4\sandbox_private_key_pkcs8.pem", "rb") as key_file:
        client_config.app_private_key == serialization.load_pem_private_key(key_file.read(), password=None)

        # 沙箱支付宝公钥（PEM格式，带头尾，多行字符串）
    #     client_config.alipay_public_key = """
    # -----BEGIN PUBLIC KEY-----
    # MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq8rRu/uaa6hZ6s7bD4qw7th8pwaWBkwignxVghsvOQOMak7nWahmB9xGuie1QFsbOZ+k7waSc1XyTDRVG+xJeVNM1gNERB5uK8lBHgAXUFgd+i98kakfDvEXXU7h2/pyJoyCeDWKwOqxLOZXspAHIgFvE1ljTMoRBjvdFccwGpeIkAcIwZ3/9H9ES61L1HCnjRczkVc5fy0f4YhzylXIElYsRaDXuxkE+t8/P40VwO86lYQbO6GBTw8UkL6X8HNGSqn6+HQt68200h4SDrsCku5GyVhTJOdV3luHO4FkjrlJx/udu2xa8SqkWTqZ4A6Qpf4QwGuUwfJOAtM1FBa3TwIDAQAB
    # -----END PUBLIC KEY-----
    # """
    with open("D:\model\P4\alipay_public_key.pem", "rb") as key_file:
        client_config.alipay_public_key == serialization.load_pem_private_key(key_file.read(), password=None)

    # ====== 支付宝沙箱环境配置结束 ======

    # ====== 调试输出密钥类型和长度 ======
    print("[调试2] app_private_key 类型:", type(client_config.app_private_key), "长度:", len(client_config.app_private_key))
    print("[调试2] alipay_public_key 类型:", type(client_config.alipay_public_key), "长度:", len(client_config.alipay_public_key))

    client = DefaultAlipayClient(alipay_client_config=client_config)

    out_biz_no = "ORDER" + uuid.uuid4().hex.upper()
    request = AlipayFundTransToaccountTransferRequest(biz_model=None)
    request.biz_content = {
        "out_biz_no": out_biz_no,
        "payee_type": "ALIPAY_LOGONID",
        "payee_account": str(user_account),  # 确保是字符串
        "amount": str(amount),               # 强制转为字符串
        "payer_show_name": "商家名称",
        "payee_real_name": str(claim_order.insurance.name),
        "remark": "保险理赔转账"
    }

    # ====== 调试输出biz_content内容和类型 ======
    print("[调试3] request.biz_content:", request.biz_content)
    print("[调试] biz_content字段：")
    for attr in dir(request.biz_content):
        if not attr.startswith('_'):
            print(f"{attr}: {getattr(request.biz_content, attr)}")

    try:
        response = client.execute(request)
        if response and response.get("code") == "10000":
            # 转账成功，更新订单
            claim_order.alipay_transfer_id = response.get("order_id", out_biz_no)
            claim_order.status = "已支付"
            claim_order.save()
            return (f"成功从商家账户 {merchant_account} 转账 {amount} 元 到用户账户 {user_account}，"
                    f"支付宝流水号：{claim_order.alipay_transfer_id}")
        else:
            # 转账失败，记录原因
            claim_order.status = "支付失败"
            claim_order.fail_reason = response.get("sub_msg", "未知错误")
            claim_order.save()
            return f"转账失败：{claim_order.fail_reason}"
    except Exception as e:
        claim_order.status = "支付失败"
        claim_order.fail_reason = str(e)
        claim_order.save()
        return f"转账异常：{str(e)}"
    # ====== 支付宝转账集成结束 ======

# 测试
last_result=alipay_transfer.invoke({
    "id_number":"110101199001010011",
    "claim_amount":"5"
})
print(last_result)

# 检查脚本：输出所有ClaimOrder的关键信息
if __name__ == "__main__":
    print("\n数据库中所有ClaimOrder：")
    for order in ClaimOrder.objects.all():
        print(f"id: {order.id}, 保险人身份证: {order.insurance.id_number}, 理赔金额: {order.claim_amount}, 状态: {order.status}, 支付宝账号: {order.insurance.alipay_account}")